package com.ygu.Enter2.topic2_3合并有序链表;

public class MergeTwoLists {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //合并两个有序链表变为一条新的链表 方法技术构造出一条新的链表来进行存储
        ListNode dummy   = new ListNode(-1);
        ListNode p = dummy;
        ListNode p1 = list1;
        ListNode p2 = list2;

        while (p1!=null && p2!=null){
            if(p1.val > p2.val){
                p.next = p2;
                p2 = p2.next;

            }else {
                //p1.val <= p2.val
                p.next = p1;
                p1 = p1.next;
            }
            p = p.next;
        }

        if (p1 != null) {
            p.next = p1;
        }

        if (p2 != null) {
            p.next = p2;
        }

        //要排除第一个值为-1的
        return dummy.next;
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
